package com.augmentum.sellproductservice.productserver.service;


import com.augmentum.sellproductserive.common.transfer.ProductInfoInput;
import com.augmentum.sellproductservice.productserver.Constants;
import com.augmentum.sellproductservice.productserver.domain.product.ProductInfo;
import com.augmentum.sellproductservice.productserver.domain.product.ProductInfoRepository;
import com.augmentum.sellproductservice.productserver.enums.ProductStatusEnum;
import com.augmentum.sellproductservice.productserver.exception.ProductException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;


@Service
@Transactional(rollbackFor = Exception.class)
public class ProductInfoService {
    @Resource
    private ProductInfoRepository productInfoRepository;

    @Autowired
    private AmqpTemplate amqpTemplate;

    public List<ProductInfo> findUpAllProductInfo() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getStatus());
    }

    public void decreaseStock(List<ProductInfoInput> productDtos) {
        productDtos.forEach(productDto -> {
            Optional<ProductInfo> optionalProductInfo = productInfoRepository.findById(productDto.getProductId());
            if (!optionalProductInfo.isPresent()) {
                throw new ProductException(HttpStatus.BAD_REQUEST.value());
            }

            ProductInfo productInfo = optionalProductInfo.get();
            if (productInfo.getProductStock() < productDto.getProductQuantity()) {
                throw new ProductException(400, "No enough stock.");
            }

            productInfo.setProductStock(productInfo.getProductStock() - productDto.getProductQuantity());
            productInfoRepository.save(productInfo);
        });

        sendDecreaseStock(productDtos);
    }

    private void sendDecreaseStock(List<ProductInfoInput> productDtos) {
        productDtos.forEach(productInfoInput -> {
            amqpTemplate.convertAndSend(Constants.PRODUCT_MSG_EXCHANGE, Constants.DECREASE_ROUTEING_KEY, productInfoInput);
        });
    }
}
